package com.deling.lib_network;

import com.deling.lib_network.cookie.SimpleCookieJar;
import com.deling.lib_network.https.HttpsUtils;
import com.deling.lib_network.listener.DisposeDataHandle;
import com.deling.lib_network.response.CommomCallback;
import com.deling.lib_network.response.CommonFileCallback;
import com.deling.lib_network.response.CommonJsonCallback;
import com.deling.lib_network.response.GsonResponseHandler;
import com.deling.lib_network.response.IResponseHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lgj
 * 2020/4/28
 * @function 用来发送get, post请求的工具类，包括设置一些请求的共用参数
 **/
public class CommonOkHttpClient {



    private static final int TIME_OUT = 30;
    private static OkHttpClient mOkHttpClient;

    static {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        /**
         *  为所有请求添加请求头，看个人需求
         */
       /* okHttpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request =
                        chain.request().newBuilder().addHeader("User-Agent", "H6-device") // 标明发送本次请求的客户端
                                .build();
                return chain.proceed(request);
            }
        });*/
        okHttpClientBuilder.cookieJar(new SimpleCookieJar());
        okHttpClientBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.followRedirects(true);
        /**
         * trust all the https point
         */
        okHttpClientBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory(),
                HttpsUtils.initTrustManager());
        mOkHttpClient = okHttpClientBuilder.build();
    }

    public static OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }



    /**
     * 通过构造好的Request,Callback去发送请求
     */
    public static Call get(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));
        return call;
    }

    /**
     * 通过构造好的Request,Callback去发送请求,泛型转换
     */
    public static Call get(Request request, IResponseHandler handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommomCallback(handle));
        return call;
    }
    /**
     * 文件下载请求
     * */
    public static Call getFile(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonFileCallback(handle));
        return call;
    }

    public static Call test_get(Request request, Callback callback){
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(callback);
        return call;
    }

    public static void cancelTag(String tag){
        if (tag == null) return;
        try {
            for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
                if(call.request()!=null){
                    if(call.request().tag()!=null){
                        if (call.request().tag().equals(tag))
                            call.cancel();
                    }
                }
            }
            for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
                if(call.request()!=null){
                    if(call.request().tag()!=null){
                        if (call.request().tag().equals(tag))
                            call.cancel();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 取消所有请求请求 */
    public void cancelAll() {
        try {
            for (Call call : getOkHttpClient().dispatcher().queuedCalls()) {
                call.cancel();
            }
            for (Call call : getOkHttpClient().dispatcher().runningCalls()) {
                call.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
